package com.ym.pms.resolvers;

import com.ym.pms.annotation.CurrentUser;
import com.ym.pms.config.Constants;
import com.ym.pms.model.SysUser;
import com.ym.pms.security.utils.JWTTokenUtil;
import com.ym.pms.service.SysUserService;
import com.ym.pms.service.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;

/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 21:00 2020/12/5
 * @Modified:
 */

@Service
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private SysUserService sysUserService;


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //如果参数类型是User并且有CurrentUser注解则支持
        return parameter.getParameterType().isAssignableFrom(SysUser.class) &&
                parameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //取出鉴权时存入的登录用户Id
        String token = (String)webRequest.getAttribute(Constants.CURRENT_USER_ID, NativeWebRequest.SCOPE_REQUEST);
        String username = JWTTokenUtil.getUserNameByToken(token);
        if(username != null){
            Long currentUserId = Long.parseLong(username);
            SysUser sysUser = sysUserService.findUserByUserId(currentUserId);
            return sysUser;
        }
        return null;
    }
}
